<template>
  <el-dialog
    class="subject-status-add-record"
    :title="dialogTitle"
    width="600px"
    :show-close="true"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <div>
      <el-form :rules="rules" ref="formRef" size="mini" :model="formData" label-width="140px">
        <!-- 是否生效 -->
        <el-form-item prop="takeEffect" label="是否生效：">
          <el-radio-group v-model="formData.takeEffect">
            <el-radio label="1">生效</el-radio>
            <el-radio label="0">失效</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 生效访视 -->
        <el-form-item prop="takeVisitId" label="生效访视：">
          <el-select v-model="formData.takeVisitId" style="width: 80%" clearable>
            <el-option
              v-for="item in takeVisitIdOptions"
              :key="item.visitNum"
              :label="item.visitName"
              :value="item.visitNum"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 聚合函数 -->
        <el-form-item prop="aggregation" label="聚合函数：">
          <el-radio-group v-model="formData.aggregation">
            <el-radio label="1">最小</el-radio>
            <el-radio label="2">最大</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 聚合范围 -->
        <el-form-item prop="aggregationScope" label="聚合范围：">
          <el-radio-group v-model="formData.aggregationScope">
            <el-radio label="1">表单级别</el-radio>
            <el-radio label="2">受试者级别</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="method" label="比较方法：">
          <el-select v-model="formData.method" style="width: 80%" clearable>
            <el-option
              v-for="item in methodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 关系表访视 -->
        <el-form-item prop="relationshipVisitId" label="关系表访视：">
          <el-select
            v-model="formData.relationshipVisitId"
            style="width: 80%"
            clearable
            @change="handleRelationshipVisitIdChange"
          >
            <el-option
              v-for="item in relationshipVisitIdOptions"
              :key="item.id"
              :value="item.id"
              :label="item.visitName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 关系表名称 -->
        <el-form-item prop="relationshipTableId" label="关系表名称：">
          <el-select
            v-model="formData.relationshipTableId"
            style="width: 80%"
            @change="handleRelationshipTableIdChange"
            clearable
          >
            <el-option
              v-for="item in relationshipTableIdOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="relationshipVariableId" label="关系表变量名：">
          <el-select v-model="formData.relationshipVariableId" style="width: 80%" clearable>
            <el-option
              v-for="item in relationshipVariableIdOptions"
              :key="item.id"
              :label="item.variableName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 是否包含边界 -->
        <el-form-item prop="boundary" label="是否包含边界：">
          <el-select v-model="formData.boundary" style="width: 80%" clearable>
            <el-option
              v-for="item in boundaryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="lowerLimit" label="下限值：">
          <el-input v-model="formData.lowerLimit" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item prop="upperLimit" label="上限值：">
          <el-input v-model="formData.upperLimit" style="width: 80%"></el-input>
        </el-form-item>

        <el-form-item prop="dateUnit" label="日期单位：">
          <el-select v-model="formData.dateUnit" style="width: 80%" clearable>
            <el-option label="月" value="1"></el-option>
            <el-option label="天" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="timeUnit" label="时间单位：">
          <el-select v-model="formData.timeUnit" style="width: 80%" :disabled="true" clearable> </el-select>
        </el-form-item>
        <!-- 质疑方式 -->
        <el-form-item prop="way" label="质疑方式：">
          <el-select size="mini" v-model="formData.way" placeholder="请选择" style="width: 80%" clearable>
            <el-option
              v-for="item in questioningModeList"
              :key="item.value"
              :value="item.value"
              :label="item.text"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogTitle === '复制'">
          <p style="color: red"><i class="el-icon-info"></i>复制前请先修改数据！</p>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button :loading="loading" size="small" type="primary" @click="handleSave">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { mapActions } from 'vuex'

export default {
  props: {
    editData: Object,
    dialogVisible: Boolean,
    dialogTitle: String,
    questioningModeList: Array,
    searchParams: Object,
  },
  data() {
    return {
      rules: {},
      loading: false,
      defaultFormData: {
        surface: '',
        domain: '',
        surfaceName: '',
        classify: '',
        quoteCrfSurface: '',
        embedded: '',
        takeEffect: '',
        aggregation: '',
        aggregationScope: '',
        method: '',
        takeVisitId: '',
        relationshipVisitId: '',
        relationshipTableId: '',
        relationshipVariableId: '',
        lowerLimit: '',
        upperLimit: '',
        boundary: '',
        dateUnit: '',
        timeUnit: '',
        way: '',
      },
      formData: {},
      methodOptions: [
        { label: '暂无', value: '0' },
        { label: '大于等于', value: '1' },
        { label: '大于', value: '2' },
        { label: '小于等于', value: '3' },
        { label: '小于', value: '4' },
        { label: '等于', value: '5' },
        { label: '不等于', value: '6' },
      ],
      boundaryOptions: [
        { label: '包含', value: '0' },
        { label: '不包含', value: '1' },
        { label: '上包含', value: '2' },
        { label: '下包含', value: '3' },
      ],
      relationshipVariableIdOptions: [],
      takeVisitIdOptions: [],
      relationshipVisitIdOptions: [],
      relationshipTableIdOptions: [],
    }
  },

  watch: {
    async dialogVisible(val) {
      if (val) {
        this.formData = this.editData.id ? { ...this.editData } : { ...this.defaultFormData }
        // 获取生效访视下拉项
        this.getTakeVisitIdOptions()
        // 获取关系表访视下拉项
        this.getRelationshipVisitIdOptions()
        // 获取关系表名称下拉项(编辑时)
        if (this.editData.relationshipVisitId) {
          const params = {
            ...this.searchParams,
            environment: '0',
            visitId: this.editData.relationshipVisitId,
            hasLoading: false,
          }
          const res = await this.getVisitTableListAPI({ params })
          if (res.code === 200) {
            this.relationshipTableIdOptions = res.data.map(item => ({
              value: item.id,
              label: item.tableName + '(' + item.tableCode + ')',
              surface: item.tableCode,
            }))
          }
        }
        // 获取关系表变量名(编辑时)
        if (this.editData.relationshipTableId) {
          const val = this.editData.relationshipTableId
          const surface = this.relationshipTableIdOptions.find(item => item.value === val).surface
          const params = {
            ...this.searchParams,
            relationshipTableId: this.formData.relationshipTableId,
          }
          params.surface = surface
          const res = await this.getTableConditionOptionsAPI({ params })
          if (res.code === 200) {
            this.relationshipVariableIdOptions = res.data
          }
        }
      } else {
        this.formData = { ...this.defaultFormData }
      }
    },
  },

  methods: {
    ...mapActions('verificationRule', [
      'copySelectListEcMultiMeterTimeComparisonAPI',
      'updateSelectListEcMultiMeterTimeComparisonAPI',
      'getVisitByCrfNameAPI',
      'geTallVisitAndTableAPI',
      'getTableConditionOptionsAPI',
      'getVisitTableListAPI',
    ]),

    // 关系表访视change
    async handleRelationshipVisitIdChange(val) {
      const params = {
        ...this.searchParams,
        environment: '0',
        visitId: val,
        hasLoading: false,
      }
      const res = await this.getVisitTableListAPI({ params })
      if (res.code === 200) {
        this.relationshipTableIdOptions = res.data.map(item => ({
          value: item.id,
          label: item.tableName + '(' + item.tableCode + ')',
          surface: item.tableCode,
        }))
        this.formData.relationshipTableId = ''
        this.formData.relationshipVariableId = ''
        this.relationshipVariableIdOptions = []
      }
    },

    // 关系表名称change
    async handleRelationshipTableIdChange(val) {
      const surface = this.relationshipTableIdOptions.find(item => item.value === val).surface
      const params = {
        ...this.searchParams,
        surface: surface,
      }
      const res = await this.getTableConditionOptionsAPI({ params })
      if (res.code === 200) {
        this.relationshipVariableIdOptions = res.data
        // 清除关系表变量名
        this.formData.relationshipVariableId = ''
      }
    },

    // 获取生效访视下拉项
    async getTakeVisitIdOptions() {
      const params = {
        ...this.searchParams,
        environment: '0',
        crfName: this.editData.surface,
      }
      const res = await this.getVisitByCrfNameAPI({ params })
      this.takeVisitIdOptions = res.data
    },

    // 获取关系表访视下拉项
    async getRelationshipVisitIdOptions() {
      const params = {
        ...this.searchParams,
        environment: '0',
      }
      const res = await this.geTallVisitAndTableAPI({ params })
      this.relationshipVisitIdOptions = res.data
    },

    // 保存提交
    handleSave() {
      this.loading = true
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.dialogTitle === '编辑') {
            const data = {
              reqDTOList: [this.formData],
            }
            this.updateSelectListEcMultiMeterTimeComparisonAPI({ data }).then(res => {
              const { code } = res
              if (code === 200) {
                this.$message({
                  message: '保存成功',
                  type: 'success',
                })
                this.$refs.formRef.resetFields()
                this.$emit('handleCancel', 'refresh')
              }
              this.loading = false
            })
          } else {
            const data = {
              ...this.formData,
            }
            this.copySelectListEcMultiMeterTimeComparisonAPI({ data }).then(res => {
              const { code } = res
              if (code === 200) {
                this.$message({
                  message: '保存成功',
                  type: 'success',
                })
                this.$refs.formRef.resetFields()
                this.$emit('handleCancel', 'refresh')
              }
              this.loading = false
            })
          }
        } else {
          this.loading = false
          return false
        }
      })
    },

    // 关闭取消
    handleClose() {
      this.formData = { ...this.defaultFormData }
      this.$emit('handleCancel')
    },
  },
}
</script>
<style lang="scss" scoped>
.span-dropdown-item {
  display: inline-block;
  width: 120%;
}
</style>
